﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;

namespace WebDataControls
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:DataTextBox runat=server></{0}:DataTextBox>")]
    public class DataTextBox : System.Web.UI.WebControls.TextBox, IDataControl
    {
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string FeildName
        {
            get
            {
                String s = (String)ViewState["FeildName"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["FeildName"] = value;
            }
        }

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string TableName
        {
            get
            {
                String s = (String)ViewState["TableName"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["TableName"] = value;
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
        }


        #region IDataControl 成员


        public void GetDataValue(ref object model)
        {
            PropertyInfo prop = model.GetType().GetProperty(this.FeildName, BindingFlags.Public | BindingFlags.Instance);
            if (null != prop && prop.CanWrite)
            {
                object value = this.Text;
                Type fieldType = WebUIHelper.GetModelFieldType(model, this.FeildName);
                if (!this.Text.GetType().Equals(fieldType))
                {
                    if (String.IsNullOrEmpty(this.Text))
                    {
                        if(fieldType.ToString()!="String")
                        {
                            this.Text = "0";
                        }

                    }
                    value = Convert.ChangeType(this.Text, fieldType);
                }
                prop.SetValue(model, value, null);

            }
        }

        public void SetDataValue(object model)
        {
            if (!String.IsNullOrEmpty(this.FeildName))
            {
                object value = model.GetType().GetProperty(this.FeildName, BindingFlags.Public | BindingFlags.Instance).GetValue(model, null);
                if (value != null)
                {
                    this.Text = value.ToString();
                }
            }
        }

        #endregion
    }
}
